﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using personalplaner.common.controls;

namespace personalplaner.gui.stamm.views
{
    /// <summary>
    /// Interaction logic for DienstZeitDialog.xaml
    /// </summary>
    public partial class DienstZeitZeitView : UserControl
    {
        public DienstZeitZeitView()
        {
            InitializeComponent();
        }

		private void MaskedTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
		{
			try
			{
				switch ((e.Source as TextBox).SelectionStart)
				{
					case 0:
						if (int.Parse(e.Text) == 2)
						{
							if (int.Parse((e.Source as TextBox).Text.Substring(1, 1)) > 3)
							{
								int index = (e.Source as TextBox).SelectionStart;
								(e.Source as TextBox).Text = (e.Source as TextBox).Text.Substring(0, 1) + "3" + (e.Source as TextBox).Text.Substring(2, 3);
								(e.Source as TextBox).SelectionStart = index;
							}
						}
						else if (int.Parse(e.Text) > 2)
							e.Handled = true;
						break;
					case 1:
						if (int.Parse((e.Source as TextBox).Text.Substring(0, 1) + e.Text) > 23)
							e.Handled = true;
						break;
					case 3:
						if (int.Parse(e.Text) == 6)
						{
							if (int.Parse((e.Source as TextBox).Text.Substring(4, 1)) > 0)
							{
								int index = (e.Source as TextBox).SelectionStart;
								(e.Source as TextBox).Text = (e.Source as TextBox).Text.Substring(0, 4) + "0";
								(e.Source as TextBox).SelectionStart = index;
							}
						}
						else if (int.Parse(e.Text) > 6)
							e.Handled = true;
						break;
					case 4:
						if (int.Parse((e.Source as TextBox).Text.Substring(3, 1) + e.Text) > 60)
							e.Handled = true;
						break;
				}
			}
			catch (FormatException)
			{
			}
		}

		private void MaskedTextBox_TextChanged(object sender, TextChangedEventArgs e)
		{
			var tb = e.Source as TextBox;
			if (tb == null)
				return;
			try
			{
				if (tb.Text.Substring(0, 2) == "23" &&
					tb.Text.Substring(3, 2) == "60")
				{
					tb.Text = "00:00";
				}
			}
			catch (ArgumentOutOfRangeException)
			{
				tb.Text = "00:00";
			}
		}
    }
}
